package cn.supermarket.security;

import cn.supermarket.web.JsonResult;
import cn.supermarket.web.State;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    //密钥

    @Value("${supermarket.jwt.secret-key}")
    private String secretKey;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        SecurityContextHolder.clearContext();
        String jwt = request.getHeader("Authentication");
        if (!StringUtils.hasText(jwt)) {
            //不存在jwt数据，放行，后续其他过滤器及相关组件对其进行处理，如未登录则进行登录请求
            filterChain.doFilter(request, response);//继续执行过滤器链中的后续过滤器
            return;
        }

        String username = null;
        String permissionsString = null;
        try {
            Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
            username = claims.get("username").toString();
            permissionsString = claims.get("permissions").toString();

        } catch (ExpiredJwtException e) {
            System.out.println("解析JWT失败，此JWT已过期：" + e.getMessage());
            JsonResult<Void> jsonResult = JsonResult.fail(State.ERR_JWT_EXPIRED, "jwt过期");
            String jsonString = JSON.toJSONString(jsonResult);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonString);
        } catch (MalformedJwtException e) {

            JsonResult<Void> jsonResult = JsonResult.fail(State.ERR_JWT_MALFORMED, "JWT格式异常");
            String jsonString = JSON.toJSONString(jsonResult);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonString);
        } catch (UnsupportedJwtException e) {
            JsonResult<Void> jsonResult = JsonResult.fail(State.ERR_JWT_UNSUPPORTED, "不支持的JWT异常");
            String jsonString = JSON.toJSONString(jsonResult);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonString);
        } catch (SignatureException e) {
            System.out.println("解析JWT失败，此JWT签名错误：" + e.getMessage());
            JsonResult<Void> jsonResult = JsonResult.fail(State.ERR_JWT_SIGNATURE, "签名异常");
            String jsonString = JSON.toJSONString(jsonResult);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonString);
        } catch (Throwable t) {
            System.out.println("未知原因导致解析失败");
            JsonResult<Void> jsonResult = JsonResult.fail(State.ERR_UNKNOWN_ERROR, "未知异常导致的错误，请稍后再试");
            String jsonString = JSON.toJSONString(jsonResult);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonString);
            t.printStackTrace();
        }
        List<SimpleGrantedAuthority> permissions = JSON.parseArray(permissionsString, SimpleGrantedAuthority.class);
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                username, null, permissions);
        SecurityContextHolder.getContext().setAuthentication(authentication);
//        filterChain.doFilter(request, response);
    }

}
